package DB::Users;

use strict;
use warnings;

use Carp; 
use DBI; 
use lib '../../lib';
use GlobalConfig;

sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;

    my $host  = shift || GlobalConfig::DB_IP;
    my $db    = shift || GlobalConfig::SCHEMA;
    my $user  = shift || GlobalConfig::DB_USER;
    my $pass  = shift || GlobalConfig::DB_PASS;

    my $self = {
        dbh => $class->connect_db($host, $db, $user, $pass)
    };

    return bless($self, $class);
}

sub connect_db {
    my $self_class = shift;
    my $host = shift;
    my $db   = shift;
    my $user = shift;
    my $pass = shift;

    my %attr = (
        PrintError => 0,
        RaiseError => 1,
    );

    my $dbh = DBI->connect("dbi:mysql:$db:$host",
        $user, $pass, \%attr);

    return $dbh;
}

sub insert {
    my $self = shift;
    croak "called without a reference" if (!ref($self));

    my ($code, $mail_account_id, $mail) = @_;
    my $sql = qq{INSERT INTO users(code, mail, mail_account_id) VALUES(?, ?, ?)};
    my $sth = $self->{dbh}->prepare($sql);
    $sth->bind_param(1, $code);
    $sth->bind_param(2, $mail);
    $sth->bind_param(3, $mail_account_id);

    eval {
        $sth->execute();
    };

    open LOG, ">>log.txt";
    print LOG "$code, $mail_account_id, $mail\n";
    print LOG $self->{dbh}->errstr . "\n" if $@;
    close LOG;

    return $@ ? undef : $self->{dbh}->last_insert_id(undef, undef, undef, undef); 
}

sub select_user_by_mail_id {
    my $self = shift;
    croak "called without a reference" if (!ref($self));

    my ($mail_account_id) = @_;
    my $sql = "SELECT * FROM users where mail_account_id = ? limit 1";
    my $sth = $self->{dbh}->prepare($sql);
    $sth->bind_param(1, $mail_account_id);
    my $rv = $sth->execute();

    if ($rv) {
        return $sth->fetchrow_hashref();
    }

    return undef; 
}

sub select_user_by_code {
    my $self = shift;
    croak "called without a reference" if (!ref($self));

    my ($code) = @_;
    my $sql = "SELECT * FROM users where code = ? limit 1";
    my $sth = $self->{dbh}->prepare($sql);
    $sth->bind_param(1, $code);
    my $rv = $sth->execute();

    if ($rv) {
        return $sth->fetchrow_hashref();
    }

    return undef; 

}

1;
